<?php

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: YagamiZN
// +----------------------------------------------------------------------

// 应用公共函数文件
include ('common/common/function.php');//常量和特殊函数
include ('common/common/encrypt_function.php');//TwoThink加密函数

/**
 * @desc 根据两点间的经纬度计算距离
 * @param float $lat 纬度值
 * @param float $lng 经度值
 * @return float 距离米
 */
function get_distance($lat1, $lng1, $lat2, $lng2){
    $earthRadius = 6367000; //approximate radius of earth in meters
    $lat1 = ($lat1 * pi() ) / 180;
    $lng1 = ($lng1 * pi() ) / 180;
    $lat2 = ($lat2 * pi() ) / 180;
    $lng2 = ($lng2 * pi() ) / 180;
    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;
    return round($calculatedDistance);
}

/**
 * 时间差天时分秒
 * @param int $startdate 开始时间戳
 * @param int $enddate 结束时间戳
 */
function time_diff( $startdate, $enddate )
{
    $date=floor(($enddate-$startdate)/86400);
    $hour=floor(($enddate-$startdate)%86400/3600);
    $minute=floor(($enddate-$startdate)%86400%3600/60);
    $second=floor(($enddate-$startdate)%86400%60);
    return $date."天".$hour."小时".$minute."分钟".$second."秒";
}

/**
 * 价格单位转万
 * @param  string  $money 要转的价格
 * @return float  $money   单位 万
 */
function format_money($money){
    if($money >= 10000){
        return sprintf("%.2f", $money/10000);
    }else{
        return $money;
    }
}

/**
 * 根据IP获取地理位置
 * @Return: array
 */
function get_city($ip = '')
{
    if($ip == ''){
        $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
        $ip=json_decode(file_get_contents($url),true);
        $data = $ip;
    }else{
        $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
        $ip=json_decode(file_get_contents($url));
        if((string)$ip->code=='1'){
            return false;
        }
        $data = (array)$ip->data;
    }

    return $data;
}

/**
 * 时间格式转化时间戳
 * @param  string  $time   要转化的时间
 * @param  string  $geshi   时间对应格式
 * @return string  时间戳
 */
function format_datetime($time,$geshi='Y-m-d'){
    return date_create_from_format($geshi,$time)->getTimestamp();
}

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 * @author 纸飞机
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[$data['id']] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][$data['id']] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 * @param  array $tree  原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array  $list  过渡用的中间数组，
 * @return array        返回排过序的列表数组
 * @author 纸飞机  <cqzfj.com>
 */
function tree_to_list($tree, $child = '_child', $order='id', &$list = array()){
    if(is_array($tree)) {
        foreach ($tree as $key => $value) {
            $reffer = $value;
            if(isset($reffer[$child])){
                unset($reffer[$child]);
                tree_to_list($value[$child], $child, $order, $list);
            }
            $list[] = $reffer;
        }
        $list = list_sort_by($list, $order, $sortby='asc');
    }
    return $list;
}

/**
 * 根据2张表的关联ID转2级菜单
 * @param  array  $list 顶级菜单
 * @param  array  $list2 2级菜单
 * @param  int  $list2 顶级菜单主键
 * @param  int  $list2 2级菜单关联主键
 * @return array  $arr   二维数组
 */
function categoty_change_two($list,$list2,$id,$pid){
    $arr=array();
    foreach ($list as $k=>$v){
        foreach ($list2 as $val){
            if($val[$pid]==$v[$id]){
                $v['child'][]=$val;
            }
        }
        $arr[]=$v;
    }
    return $arr;
}

/**
 * 生成订单号
 * @param string $type 订单号类型
 * 1：13位订单号 2：16位订单号 3:BG16位
 * @return order_no
 * @author YagamiZN
 */
function create_order_no($type){
    if($type==1){
        return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }elseif ($type==2){
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }elseif($type==3){
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $orderSn;
    }
}

/**
 * Excel数据导出
 * @param array $title   标题行名称
 * @param array $data   导出数据
 * @param string $fileName 文件名
 * @param string $savePath 保存路径
 * @param bool $isDown   是否下载  false--保存   true--下载
 * @return string   返回文件全路径
 * @throws PHPExcel_Exception
 * @throws PHPExcel_Reader_Exception
 * exportExcel(array('姓名','年龄'), array(array('a',21),array('b',23)), '档案', './', true)
 */
function exportExcel($title=array(), $data=array(), $fileName='', $savePath='./', $isDown=false){
    Vendor('PHPExcel.Classes.PHPExcel');
    Vendor('PHPExcel.Classes.PHPExcel.IOFactory');
    $obj=new \PHPExcel();
    //横向单元格标识
    $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
    $obj->getActiveSheet(0)->setTitle('sheet1');   //设置sheet名称
    $_row = 1;   //设置纵向单元格标识
    if($title){
        $_cnt = count($title);
        $obj->getActiveSheet(0)->mergeCells('A'.$_row.':'.$cellName[$_cnt-1].$_row);   //合并单元格
        $obj->getActiveSheet(0)->getStyle('A1')->getFont()->getColor()->setARGB('FFFF0000'); //设置颜色  
        $obj->setActiveSheetIndex(0)->setCellValue('A'.$_row, '数据导出：'.date('Y-m-d H:i:s'));//设置合并后的单元格内容
        $_row++;
        $i = 0;
        foreach($title AS $v){   //设置列标题
            foreach ($cellName as $vv){
                $obj->setActiveSheetIndex(0)->getStyle($vv.'2')//设置字体
                ->getFont()
                //->setName('宋体') //字体
                //->setSize(12) //字体大小
                ->setBold(true); //字体加粗
                $obj->setActiveSheetIndex(0)->getColumnDimension($vv)//设置单元格宽
                ->setAutoSize(true);
                $obj->setActiveSheetIndex(0)
                ->getStyle($vv.$_row)->getAlignment()//对齐方式
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//水平居中
            }
            $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);
            $i++;
        }
        $_row++;
    }
    //填写数据
    if($data){
        $i = 0;
        foreach($data AS $_v){
            $j = 0;
            foreach($_v AS $_cell){
                //填写数据之前可单独设置格式
                $obj->getActiveSheet(0)->setCellValue($cellName[$j] . ($i+$_row), $_cell);
                $j++;
            }
            $i++;
        }
    }
    //文件名处理
    if(!$fileName){
        $fileName = uniqid(time(),true);
    }
    $objWrite = \PHPExcel_IOFactory::createWriter($obj, 'Excel5');
    if($isDown){   //网页下载
        ob_end_clean();
        header('pragma:public');
        header("Content-Disposition:attachment;filename=$fileName.xls");
        header('Cache-Control: max-age=0');
        $objWrite->save('php://output');exit;
    }
    $_fileName = iconv("utf-8", "gb2312", $fileName);   //转码
    $_savePath = $savePath.$_fileName.'.xls';
    $objWrite->save($_savePath);
    return $savePath.$fileName.'.xls';
}

/**
 * Excel数据导入
 * @param string $file excel文件
 * @param string $sheet
 * @return string   返回解析数据
 * @throws PHPExcel_Exception
 * @throws PHPExcel_Reader_Exception
 */
function importExecl($file='', $sheet=0){
    $file = iconv("utf-8", "gb2312", $file);   //转码
    if(empty($file) OR !file_exists($file)) {
        die('file not exists!');
    }
    Vendor('PHPExcel.Classes.PHPExcel');  //引入PHP EXCEL类
    $objRead = new PHPExcel_Reader_Excel2007();   //建立reader对象
    if(!$objRead->canRead($file)){
        $objRead = new PHPExcel_Reader_Excel5();
        if(!$objRead->canRead($file)){
            die('No Excel!');
        }
    }
    $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
    $obj = $objRead->load($file);  //建立excel对象
    $currSheet = $obj->getSheet($sheet);   //获取指定的sheet表
    $columnH = $currSheet->getHighestColumn();   //取得最大的列号
    $columnCnt = array_search($columnH, $cellName);
    $rowCnt = $currSheet->getHighestRow();   //获取总行数
    $data = array();
    for($_row=1; $_row<=$rowCnt; $_row++){  //读取内容
        for($_column=0; $_column<=$columnCnt; $_column++){
            $cellId = $cellName[$_column].$_row;
            $cellValue = $currSheet->getCell($cellId)->getValue();
            //$cellValue = $currSheet->getCell($cellId)->getCalculatedValue();  #获取公式计算的值
            if($cellValue instanceof PHPExcel_RichText){   //富文本转换字符串
                $cellValue = $cellValue->__toString();
            }

            $data[$_row][$cellName[$_column]] = $cellValue;
        }
    }
    return $data;
}